package com.icms.common.beetl;

import com.icms.common.beetl.tag.ChannelListTag;
import com.icms.common.beetl.tag.ChannelTag;
import com.icms.common.beetl.tag.ContentListTag;
import com.icms.common.beetl.tag.ContentPageTag;
import com.icms.common.beetl.tag.ContentTag;
import com.icms.common.beetl.tag.ModelFiledTag;
import com.icms.common.beetl.tag.PaginationTag;
import com.icms.common.beetl.tag.ShiroTag;
import com.jfinal.kit.PathKit;
import com.jfinal.render.IMainRenderFactory;
import com.jfinal.render.Render;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.FileResourceLoader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class BeetlRenderFactory implements IMainRenderFactory {
	public static String viewExtension = ".html";
	public static GroupTemplate gt = null;
	public static Map<String, Object> siteVar = new HashMap<String, Object>();
	
	public BeetlRenderFactory() {

		String file = PathKit.getWebRootPath() + "/WEB-INF/t";
		Configuration cfg;

		try {
			cfg = Configuration.defaultConfiguration();
			cfg.setCharset("UTF-8");
			cfg.setPlaceholderStart("${");
			cfg.setPlaceholderEnd("}");
			cfg.setStatementStart("@");
			cfg.setStatementEnd(null);
			FileResourceLoader resourceLoader = new FileResourceLoader(file);
			gt = new GroupTemplate(resourceLoader, cfg);
//			gt.setErrorHandler(new WebErrorHandler());
			siteVar.put("powered", "ICMS");
			gt.registerFunctionPackage("shiro", new ShiroTag());
			gt.registerTag("cms_content",ContentTag.class);
			gt.registerTag("cms_content_list",ContentListTag.class);
			gt.registerTag("cms_content_page",ContentPageTag.class);
			gt.registerTag("cms_pagination",PaginationTag.class);
			gt.registerTag("cms_channel",ChannelTag.class);
			gt.registerTag("cms_channel_list",ChannelListTag.class);
			gt.registerTag("cms_model_filed",ModelFiledTag.class);
			gt.setSharedVars(siteVar);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Render getRender(String view) {
		return new BeetlRender(gt, view);
	}

	public String getViewExtension() {
		return viewExtension;
	}

}
